<?php

class user_rebateModel extends Model 
{
    const POINT_TYPE_DYNAMIC = 1;
    const POINT_TYPE_SHARE_DYNAMIC = 2;
    const POINT_TYPE_SHARE_GOODS = 3;
    
    const STATUS_UNUSE = 0;
    const STATUS_USED = 1;
    
    public function addRebate($buid) {
        $dynamicId = intval(Request::getParams('dynamicId'));
        $goodsId = intval(Request::getParams('goodsId'));
        $suid = intval(Request::getParams('suid'));
        if(!$goodsId||!$buid) {
            return ;
        }
        if(!$goodsInfo = self::model('goods')->getOne('goods_id=?', $goodsId)){
            return ;
        }
        if($dynamicId) {
            $dynamicInfo = self::model('dynamic')->fields('uid, dynamic_id')->getOne('dynamic_id=?', $dynamicId);
            if($dynamicInfo) {
                $this->insert([
                    'suid' => $dynamicInfo['uid'],
                    'buid' => $buid,
                    'goods_id' => $goodsId,
                    'point_type' => self::POINT_TYPE_DYNAMIC,
                    'point' => 0,
                    'status' => self::STATUS_UNUSE,
                    'add_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                ]);
            }
        }
        if($suid) {
           $this->insert([
                'suid' => $suid,
                'buid' => $buid,
                'goods_id' => $goodsId,
                'point_type' => $dynamicInfo?self::POINT_TYPE_SHARE_DYNAMIC:self::POINT_TYPE_SHARE_GOODS,
                'point' => 0,
                'status' => self::STATUS_UNUSE,
                'add_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
            ]);
        }
        return ;
    }
    
    public function getAllRebate($buid, $goodsId) {
        $sql = "select t.* from (select * from wf_user_rebate where `buid`={$buid} and `goods_id`={$goodsId} and `status`=0 and `point_type`=1 order by id asc limit 1) t union ALL "
            ."select t.* from (select * from wf_user_rebate where `buid`={$buid} and `goods_id`={$goodsId} and `status`=0 and `point_type`=2 order by id asc limit 1) t union All "
            ."select t.* from (select * from wf_user_rebate where `buid`={$buid} and `goods_id`={$goodsId} and `status`=0 and `point_type`=3 order by id asc limit 1) t ";
        return $this->query($sql)->fetchAll();
    }
    
    public function updateIds($ids) {
        $ids = implode(',', $ids);
        $sql = "update wf_user_rebate set status=1 where id in ({$ids})";
        return $this->execute($sql); 
    }
    
    public function updateUserRebate($buid, $goodsId) {
        return $this->update([
            'status' => self::STATUS_USED
        ],'buid=? and goods_id=?', [$buid, $goodsId]);
    }
}